import { 
  search, 
  getSuggestions, 
  getHotSearches, 
  recordSearch, 
  getSearchHistory,
  clearSearchHistory
} from '@/api/search'

// 如果浏览器支持localStorage，从本地缓存获取历史记录
const localHistory = localStorage.getItem('searchHistory')
const initialHistory = localHistory ? JSON.parse(localHistory) : []

const state = {
  searchHistory: initialHistory,
  hotSearches: [],
  suggestions: [],
  results: [],
  loading: false,
  totalCount: 0
}

const mutations = {
  SET_SEARCH_HISTORY(state, history) {
    state.searchHistory = history
    // 同步到localStorage
    localStorage.setItem('searchHistory', JSON.stringify(history))
  },
  
  ADD_SEARCH_HISTORY(state, keyword) {
    // 如果已存在，先移除
    const index = state.searchHistory.indexOf(keyword)
    if (index !== -1) {
      state.searchHistory.splice(index, 1)
    }
    
    // 添加到头部
    state.searchHistory.unshift(keyword)
    
    // 限制最大长度为10
    if (state.searchHistory.length > 10) {
      state.searchHistory.pop()
    }
    
    // 同步到localStorage
    localStorage.setItem('searchHistory', JSON.stringify(state.searchHistory))
  },
  
  CLEAR_SEARCH_HISTORY(state) {
    state.searchHistory = []
    // 同步到localStorage
    localStorage.removeItem('searchHistory')
  },
  
  SET_HOT_SEARCHES(state, searches) {
    state.hotSearches = searches
  },
  
  SET_SUGGESTIONS(state, suggestions) {
    state.suggestions = suggestions
  },
  
  SET_RESULTS(state, results) {
    state.results = results
  },
  
  SET_LOADING(state, status) {
    state.loading = status
  },
  
  SET_TOTAL_COUNT(state, count) {
    state.totalCount = count
  }
}

const actions = {
  // 执行搜索
  async doSearch({ commit }, { keyword, params = {} }) {
    if (!keyword || keyword.trim() === '') {
      commit('SET_RESULTS', [])
      commit('SET_TOTAL_COUNT', 0)
      return { items: [], total: 0 }
    }
    
    commit('SET_LOADING', true)
    try {
      // 将关键词和其他参数合并
      const searchParams = { keyword, ...params }
      const response = await search(searchParams)
      
      commit('SET_RESULTS', response.items || [])
      commit('SET_TOTAL_COUNT', response.total || 0)
      
      // 记录搜索历史
      commit('ADD_SEARCH_HISTORY', keyword)
      
      // 可选：将搜索历史同步到服务器
      try {
        await recordSearch(keyword)
      } catch (e) {
        console.warn('记录搜索历史到服务器失败', e)
      }
      
      return response
    } catch (error) {
      console.error('搜索失败', error)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取搜索建议
  async fetchSuggestions({ commit }, keyword) {
    if (!keyword || keyword.trim() === '') {
      commit('SET_SUGGESTIONS', [])
      return []
    }
    
    try {
      const suggestions = await getSuggestions(keyword)
      commit('SET_SUGGESTIONS', suggestions)
      return suggestions
    } catch (error) {
      console.error('获取搜索建议失败', error)
      return []
    }
  },
  
  // 获取热门搜索
  async fetchHotSearches({ commit }) {
    try {
      const hotSearches = await getHotSearches()
      commit('SET_HOT_SEARCHES', hotSearches)
      return hotSearches
    } catch (error) {
      console.error('获取热门搜索失败', error)
      return []
    }
  },
  
  // 获取搜索历史
  async fetchSearchHistory({ commit }) {
    try {
      // 尝试从服务器获取，如果失败则使用本地缓存
      const history = await getSearchHistory()
      if (history && history.length > 0) {
        commit('SET_SEARCH_HISTORY', history)
      }
      return history
    } catch (error) {
      console.warn('获取搜索历史失败，使用本地缓存', error)
      return state.searchHistory
    }
  },
  
  // 添加搜索历史
  addSearchHistory({ commit }, keyword) {
    if (!keyword || keyword.trim() === '') return
    
    commit('ADD_SEARCH_HISTORY', keyword)
    
    // 可选：将搜索历史同步到服务器
    try {
      recordSearch(keyword)
    } catch (e) {
      console.warn('记录搜索历史到服务器失败', e)
    }
  },
  
  // 清除搜索历史
  async clearSearchHistory({ commit }) {
    commit('CLEAR_SEARCH_HISTORY')
    
    // 可选：同步到服务器
    try {
      await clearSearchHistory()
    } catch (e) {
      console.warn('清除服务器搜索历史失败', e)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 